package com.defysoft.waukids.main;


import java.util.ArrayList;

import org.json.JSONObject;

import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.defysoft.waukids.BaseActivity;
import com.defysoft.waukids.Custom_Data_Type.WK_STUDENT;
import com.defysoft.waukids.Data_Sharedpreferences;
import com.defysoft.waukids.JsonParser;
import com.defysoft.waukids.PublicSharedpreferences;
import com.defysoft.waukids.R;
import com.defysoft.waukids.Sqlite_Connect;
import com.nostra13.universalimageloader.cache.disc.naming.Md5FileNameGenerator;
import com.nostra13.universalimageloader.cache.memory.impl.LruMemoryCache;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.QueueProcessingType;

public class Main_Student_Change extends BaseActivity{
	Toolbar toolbar;
	ListView lv;
	PublicSharedpreferences psf;
	SharedPreferences.Editor editor;
	public Data_Sharedpreferences.SF_Member member;
	public Data_Sharedpreferences.SF_Student student;
	ArrayList<WK_STUDENT> list_student;
	Student_ListAdapter stu_adapter;
	private final int SUCCESS = 7;
	private final int FAIL = 8;
	private final int CATCH_EXCEPTION = 9;
	private final int SUCCESS_CONNECT = 6;
	private ImageLoader imageLoader;
	DisplayImageOptions defaultOptions;
	int connect_pos=0;
	String connect;
	public Sqlite_Connect sqlite_Connect;
	@Override
	protected void onCreate(Bundle arg0) {
		super.onCreate(arg0);
		setContentView(R.layout.main_student_select);
		setStartData();
		setToolbar();
		setImageinit();
		startNetwork(0);
	}
	
	@Override
	public void setStartData() {
		super.setStartData();
		sqlite_Connect = new Sqlite_Connect(this);
		lv = (ListView)findViewById(R.id.STUDENT_SELECT_LIST);
		psf = new PublicSharedpreferences(this);
		psf.setMembersp();
		psf.setStudentsp();
		member = psf.getMembersp();
		student = psf.getStudentsp();
		list_student = new ArrayList<WK_STUDENT>();
		stu_adapter= new Student_ListAdapter();
		lv.setAdapter(stu_adapter);
		lv.setDivider(null);
	}
	private void setToolbar() {
		toolbar = (Toolbar)findViewById(R.id.MAIN_MAIN_TOOLBAR);
		toolbar.setNavigationOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
					finish();
			}
		});
	}
	
	public void setImageinit(){
		defaultOptions = new DisplayImageOptions.Builder().cacheInMemory(true)
				.cacheOnDisk(true).imageScaleType(ImageScaleType.EXACTLY)
				.considerExifParams(true)
				.bitmapConfig(Bitmap.Config.RGB_565).build();
	
	ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
			this).threadPriority(Thread.NORM_PRIORITY - 2)
			.denyCacheImageMultipleSizesInMemory()
			.memoryCache(new LruMemoryCache(2 * 1024 * 1024))
			.memoryCacheSize(2 * 1024 * 1024)
			.memoryCacheSizePercentage(20)
			.defaultDisplayImageOptions(defaultOptions)
			.diskCacheSize(50 * 1024 * 1024)
			.diskCacheFileCount(100)
			 .diskCacheExtraOptions(480, 320, null) 
			.diskCacheFileNameGenerator(new Md5FileNameGenerator())
			.tasksProcessingOrder(QueueProcessingType.LIFO)
			.writeDebugLogs() // Remove for release app
			.build();
	
	imageLoader = ImageLoader.getInstance();
/*		imageLoader.clearDiskCache();
	imageLoader.clearMemoryCache();*/
	imageLoader.init(config);
	}
	void mainThread(){
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code="+ MAIN_CHILD_SELECT
					+"&Stu_Email="+ member.Email +"&FK_Sch_Stu_Code="+member.School ));
			if (jsonObject.getBoolean("success")) {
				list_student = JsonParser.Student_List(jsonObject.getString("payload"));
				onNetworkCallback(SUCCESS, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION,e.toString()+" where mainThread()");
		}
	}
	
	void upThread(){
		try {
			JSONObject jsonObject = new JSONObject(publicHttpCallback(HTTP_URL,
					"code="+ CODE_MAIN_STUDENT_CONNECT
					+"&PK_Mem_Email="+ member.Email +"&connect="+connect ));
			if (jsonObject.getBoolean("success")) {
				onNetworkCallback(SUCCESS_CONNECT, "");
			} else {
				onNetworkCallback(FAIL, jsonObject.getString("message"));
			}
		} catch (Exception e) {
			onNetworkCallback(CATCH_EXCEPTION, e.toString()+" where upThread()");
		}
	}
	
	
	@Override
	public void startThread(int choice) {
		super.startThread(choice);
		final int cho = choice;
		firstThread = new Thread(new Runnable() {
			
			@Override
			public void run() {
				switch (cho) {
				case 0:					
					mainThread();
					break;
				case 1:
					upThread();
					break;
				}
			}
		});
		firstThread.start();
		startDIal();
	}

	@Override
	protected void handlingMessage(Message _message) {
		super.handlingMessage(_message);
		
		switch (_message.what) {
		
		case SUCCESS:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			stu_adapter.notifyDataSetChanged();
			break;
		
		case SUCCESS_CONNECT:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			update_share(connect_pos);
			endDIal();
		case FAIL:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			//Toast.makeText(this,(String)_message.obj, Toast.LENGTH_SHORT).show();
			break;
		case CATCH_EXCEPTION:
			if (firstThread != null) {
				firstThread.interrupt();
			}
			endDIal();
			sqlite_Connect.insert_Err_Log((String)_message.obj,android.os.Build.VERSION.SDK_INT,"Main_Student_Change", member.Email);
			break;
		}
	}

	
	class Student_ListAdapter extends ArrayAdapter<String>{

		public Student_ListAdapter() {
			super(Main_Student_Change.this, android.R.layout.simple_list_item_1);
			// TODO Auto-generated constructor stub
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return list_student.size();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			Student_Holder holder;
			final int pos = position;
				if(convertView==null){
					holder = new Student_Holder();
					convertView = getLayoutInflater().inflate(R.layout.student_list_row, null);
					holder.ly = (LinearLayout)convertView.findViewById(R.id.STUDENT_LIST_CONTAINER);
					holder.iv = (ImageView)convertView.findViewById(R.id.STUDENT_LIST_IV);
					holder.tv = (TextView)convertView.findViewById(R.id.STUDENT_LIST_TV);
					convertView.setTag(holder);
				}else{
					holder = (Student_Holder)convertView.getTag();
				}
			
				holder.iv.setImageResource(0xff8bc540);
				imageLoader.displayImage(HTTP_URL_STUDENTPHOTO+list_student.get(position).Stu_Photo,holder.iv,defaultOptions);
				holder.tv.setText(list_student.get(position).Stu_Name);
				
				if(student.Code.equals(list_student.get(pos).PK_Stu_Code)){	
					holder.ly.setBackgroundColor(0xaa000000);
				}else{
					holder.ly.setBackgroundColor(0xffffffff);
					holder.ly.setOnClickListener(new OnClickListener() {					
						@Override
						public void onClick(View v) {
							
								alertDialog(pos);
						}
					});
				}	
			return convertView;
		}
	}
	
	class Student_Holder{
		ImageView iv;
		TextView tv;
		LinearLayout ly;
	}
	
	// 네.아니오.선택다이얼로그
				void alertDialog(final int pos) {
					
					AlertDialog.Builder builder = new AlertDialog.Builder(
							this);
					AlertDialog alert;
					builder.setMessage("원아 변경을 하시겠습니까?")
							.setCancelable(false)
							.setPositiveButton("네", new DialogInterface.OnClickListener() {

								@Override
								public void onClick(DialogInterface dialog, int which) {
									connect_pos = pos;
									editor = psf.getMember_edit();
									editor.putString(PublicSharedpreferences.SF_Member_Key.CONNECT, list_student.get(pos).PK_Stu_Con_Code);
									editor.commit();
									psf.setMembersp();
									member = psf.getMembersp();
									connect = member.Connect;
									startNetwork(1);
								
								}
							})
							.setNegativeButton("아니오",
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(DialogInterface dialog,
												int which) {
											dialog.cancel();
										}
									});
					alert = builder.create();
					alert.show();
				}
				
	void update_share(final int pos){
		
		
		
		psf.delStudentsp();
		editor = psf.getStudent_edit();
		
		editor.putString(PublicSharedpreferences.SF_Student_Key.BIRTH,
				list_student.get(pos).Stu_Birth);
		editor.putString(PublicSharedpreferences.SF_Student_Key.CLASS,
				list_student.get(pos).FK_Cla_Stu_Code);
		editor.putString(PublicSharedpreferences.SF_Student_Key.CODE,
				list_student.get(pos).PK_Stu_Code);
		editor.putString(PublicSharedpreferences.SF_Student_Key.EMAIL,
				list_student.get(pos).Stu_Email);
		editor.putString(PublicSharedpreferences.SF_Student_Key.INFO,
				list_student.get(pos).Stu_Info);
		editor.putString(PublicSharedpreferences.SF_Student_Key.NAME,
				list_student.get(pos).Stu_Name);
		editor.putString(PublicSharedpreferences.SF_Student_Key.PHOTO,
				list_student.get(pos).Stu_Photo);
		editor.putString(
				PublicSharedpreferences.SF_Student_Key.RAN_STUCODE,
				list_student.get(pos).Rand_PK_Stu_Code);
		editor.putString(PublicSharedpreferences.SF_Student_Key.SCHOOL,
				list_student.get(pos).FK_Sch_Stu_Code);
		editor.commit();
		
		editor = psf.getMember_edit();
		editor.putString(PublicSharedpreferences.SF_Member_Key.CLASS, list_student.get(pos).FK_Cla_Stu_Code);
		editor.commit();
		
		setResult(REFRESH_CODE);
		
		finish();
	}
}
